package com.wlc.io;

import java.io.*;

/**
 * @author 王立朝 wanglichao@champion-credit.com
 * @description 对象输出流对象输入流
 * @date 2021-07-10 17:10
 */
public class ObjectStream {

    private static final String FILE_PATH = "/Users/wanglichao/Desktop/temp/test5.txt";

    public static void method01() {
        Hero hero = new Hero();
        hero.name = "盖伦";
        hero.hp = 100;
        File file = new File(FILE_PATH);

        try (
                // 创建对象输出流
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
                // 创建对象输入流
                FileInputStream fileInputStream = new FileInputStream(file);
                ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)

        ) {

            // 输出对象
            objectOutputStream.writeObject(hero);
            // 输入对象
            Hero hero1 = (Hero) objectInputStream.readObject();
            System.out.println("hero1.name = " + hero1.name);
            System.out.println("hero1.hp = " + hero1.hp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 定义一个对象数组，然后把对象数组输出到一个文件中，然后反序列化读取出来
     */
    public static void method02() {
        Hero[] heroes = new Hero[10];
        for (int i = 0; i < heroes.length; i++) {
            heroes[i] = new Hero();
            heroes[i].name = "张三" + i;
            heroes[i].hp = i;
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(FILE_PATH);
             // 定义对象输出流
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
             // 定义文件输入流
             FileInputStream fileInputStream = new FileInputStream(FILE_PATH);
             // 定义对象输入流
             ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
            // 把对象输出到文件中
            objectOutputStream.writeObject(heroes);
            // 对象写入完成
            System.out.println("对象写入完成");
            // 读取对象数组
            Hero[] heroes1 = (Hero[]) objectInputStream.readObject();
            for (int i = 0; i < heroes1.length; i++) {
                System.out.println("反序列化读取到的对象名称为： " + heroes1[i].name + " 对象hp为： " + heroes1[i].hp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        method01();
    }
}
